import time

import requests

from .constants import BROWSER_USER_AGENT


class OnethingLogin:
    SMS_SEND_URL = "https://account.onethingcloud.com/v5/sms/send"
    USER_SMS_LOGIN_URL = "https://account.onethingcloud.com/v5/user/smslogin"

    DEFAULT_HEADERS = {
        "User-Agent": BROWSER_USER_AGENT,
        "Origin": "https://www.onethingcloud.com",
        "Referer": "https://www.onethingcloud.com/",
        "Accept": "application/json",
        "Content-Type": "application/json; charset=utf-8",
        "Accept-Encoding": "gzip",
        "Accept-Language": "zh-CN,zh;q=0.9",
    }

    DEFAULT_REQUEST_MODEL = {
        "appId": "22017",
        "appName": "网心云",
        "clientVer": "115.0.0.0",
        "deviceModel": "PC-model",
        "platType": "0",
        "deviceSign": "ec625ac1fc4f05487d95a1f04a91cd31",
        "deviceName": "Chrome",
        "OSVer": "Windows10",
        "isp": "NONE",
        "netType": "OTHER"
    }

    def __init__(self):
        session = requests.session()
        session.headers.update(self.DEFAULT_HEADERS)
        self.session = session

    def send_verification_code(self, phone: str):
        request_model = self.DEFAULT_REQUEST_MODEL.copy()
        request_model.update({
            "type": 30,
            "phone": phone,
            "timestamp": int(time.time() * 1000),
        })
        response = self.session.post(self.SMS_SEND_URL, json=request_model)
        response.raise_for_status()
        return response.json()

    def login(self, tk: str, phone: str, sms_code: str):
        request_model = self.DEFAULT_REQUEST_MODEL.copy()
        request_model.update({
            "type": 1,
            "tk": tk,
            "phone": phone,
            "smsCode": sms_code,
            "timestamp": int(time.time() * 1000),
        })
        session = self.session
        session.cookies["tk"] = tk
        response = session.post(self.USER_SMS_LOGIN_URL, json=request_model)
        response.raise_for_status()
        return response.json()
